package com.yutel.multher.reaper.task;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yutel.multher.reaper.ReaperServer;
import com.yutel.multher.reaper.domain.TaskData;
import com.yutel.multher.reaper.listener.OnAutoListener;

public class AutarkicTask<T extends TaskData> implements Runnable {
	private static final Logger log = LoggerFactory
			.getLogger(AutarkicTask.class);
	private int oldCount = 0;
	private int queueMin;
	private int queueInterval;
	private OnAutoListener<T> autoListener;

	public AutarkicTask(ReaperServer<T> reaperServer) {
		queueMin = reaperServer.getQueueMin();
		queueInterval = reaperServer.getQueueInterval();
		autoListener = reaperServer.getOnAutoListener().NewTask();
	}

	@Override
	public void run() {
		while (true) {
			List<T> list = null;
			try {
				synchronized (AutarkicTask.class) {
					list = autoListener.OnDataLoad(queueMin);
				}
				int newCount = list.size();
				if (oldCount == 0 && newCount == 0) {
					log.debug("task sleep time:{}", queueInterval);
					Thread.sleep(queueInterval);
				} else {
					for (T t : list) {
						autoListener.OnTaskProcess(t);
					}
					if (newCount > 0) {
						log.info("task process finished:{}", newCount);
					}
				}
				oldCount = newCount;
			} catch (InterruptedException e) {
				log.error("server is shutdown", e);
				autoListener.OnDataEnd(list);
			} catch (Exception e) {
				log.error("run error", e);
			}
		}
	}

}
